package files;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections4.MapUtils;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @ClassName: JsonToNewJson
 * @Description: 核心json报文转json报文示例
 * @Author: zyy
 * @Date: 2020/08/16 13:41
 * @Version: 1.0
 */
public class JsonToNewJson {


    public static final String RESPONSE_CODE_SUCCESS = "999999";

    public static void main(String[] args) {
        //准备数据
        List<Map<String, Object>> paramInList = getParamInList();
        System.out.println("----入参报文：" + paramInList);

        //deal
        JSONObject jsonObject = paramInListToJSONUtil.deal(paramInList);
        System.out.println(jsonObject);

    }

    private static List<Map<String, Object>> getParamInList() {
        String jsonString = null;
        try (InputStream inputStream = new FileInputStream("D:\\document\\json.txt");
             InputStreamReader streamReader = new InputStreamReader(inputStream);
             BufferedReader bufferedReader = new BufferedReader(streamReader)) {
            StringBuffer stringBuffer = new StringBuffer();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
            }
            jsonString = stringBuffer.toString();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //--JSON String to Map
        Map<String, Object> paramMap = JSONObject.parseObject(jsonString);
        String responseCode = Optional.ofNullable(paramMap)
                .map(map -> (String) map.get("responseCode"))
                .orElse(null);
        if (!RESPONSE_CODE_SUCCESS.equals(responseCode)) {
            return null;
        }
        Map<String, Object> applyMap = Optional.ofNullable(paramMap)
                .map(map -> (Map<String, Object>) map.get("result"))
                .map(resultMap -> (Map<String, Object>) resultMap.get("APPLY"))
                .orElse(null);
        if (MapUtils.isEmpty(applyMap)) {
            return null;
        }
        return (List<Map<String, Object>>) applyMap.get("paramIn");

    }
}
